<?php

namespace Database\Seeders;

use Illuminate\Database\Seeder;
use App\Models\AfterSalesRequest;
use App\Models\AfterSalesItem;
use App\Models\AfterSalesApproval;
use App\Models\Order;

class AfterSalesSeeder extends Seeder
{
    /**
     * Run the database seeds.
     */
    public function run(): void
    {
        // 只为已发货或已送达的订单创建售后
        $orders = Order::with('items')
            ->whereIn('status', ['shipped', 'delivered'])
            ->get();

        if ($orders->isEmpty()) {
            $this->command->info('没有可申请售后的订单');
            return;
        }

        $typesAndStatuses = [
            ['type' => 'return', 'status' => 'pending'],
            ['type' => 'refund', 'status' => 'approved'],
            ['type' => 'exchange', 'status' => 'processing', 'extended_status' => 'return_shipped'],
        ];

        // 创建3个售后申请
        foreach ($typesAndStatuses as $index => $config) {
            if ($index >= $orders->count()) {
                break;
            }

            $order = $orders[$index];
            $orderItem = $order->items->random();

            $request = AfterSalesRequest::create([
                'order_id' => $order->id,
                'user_id' => $order->user_id,
                'type' => $config['type'],
                'reason' => $this->getReasonForType($config['type']),
                'status' => $config['status'],
                'extended_status' => $config['extended_status'] ?? null,
                'requested_amount' => $orderItem->total_amount,
            ]);

            // 创建售后商品项
            AfterSalesItem::create([
                'request_id' => $request->id,
                'order_item_id' => $orderItem->id,
                'quantity' => $orderItem->quantity,
                'original_price' => $orderItem->price,
                'refund_amount' => $orderItem->total_amount,
            ]);

            // 为已批准的创建审批记录
            if ($config['status'] === 'approved' || $config['status'] === 'processing') {
                AfterSalesApproval::create([
                    'request_id' => $request->id,
                    'admin_id' => 1,
                    'action' => 'approve',
                    'reason' => '符合售后条件，予以批准',
                ]);
                
                // 更新售后申请的批准金额
                $request->update([
                    'approved_amount' => $orderItem->total_amount,
                    'approved_at' => now()->subHours(rand(1, 24)),
                ]);
            }

            $this->command->info("✅ 创建了{$config['type']}售后申请，状态：{$config['status']}");
        }
    }

    private function getReasonForType(string $type): string
    {
        return match($type) {
            'return' => '商品质量问题',
            'refund' => '不需要了',
            'exchange' => '尺寸不合适',
            default => '其他原因',
        };
    }
}
